<?php
namespace app\api\controller;
use app\common\controller\CommonApi;

/**
 * 优惠券模块
 */
class Coupon extends CommonApi{
    protected $tn = 'common/coupon';

    /**
     * [发布优惠券]
     * @return [type] [description]
     */
    public function issue(){
        $validate = validate($this->tn);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $model = db('coupon')->where('user_id',UID);
        //发布折扣券限制
        if($this->user_info['grade'] == 0){
            $fabu_num = db('web_config')->where('key','p_zhekou_fabu')->value('value');
            $shuliang = db('web_config')->where('key','p_zhekou_shuliang')->value('value');
            $model->whereTime('add_time','y');
        }else{
            $fabu_num = db('web_config')->where('key','h_zhekou_fabu')->value('value');
            $shuliang = db('web_config')->where('key','h_zhekou_shuliang')->value('value');
            $model->whereTime('add_time','m');
        }

        $issue_num = $model->count();

        if($fabu_num <= $issue_num){
            $this->apiReturn(0,'发布次数达到上限');
        }

        if(intval($this->post['i_num']) <= 0 || intval($this->post['i_num']) > $shuliang){
            $this->apiReturn(0,'一次最多可发布'.$shuliang.'张');
        }

        if(floatval($this->post['z_num']) <= 0){
            $this->apiReturn(0,'请输入折扣额度');
        }

        if(strtotime($this->post['end_use']) < strtotime($this->post['start_use'])){
            $this->apiReturn(0,'截止时间不得小于开始时间');
        }


        if($this->post['jump'] != 3){
            if(!isset($this->post['foreign_key']) || intval($this->post['foreign_key']) <= 0){
                $this->apiReturn(0,'请选择跳转项');
            }
            if($this->post['jump'] == 1){
                $model = model('comment/service');
            }else{
                $model = model('comment/need');
            }

            $info = $model->where('id',intval($this->post['foreign_key']))->where('user_id',UID)->where('status',1)->find();
            if(is_null($info)){
                $this->apiReturn(0,'跳转项不存在');
            }
        }

        $this->post['user_id'] = UID;
        $this->post['get_num'] = intval($this->post['i_num']);
        
        if(!model($this->tn)->allowField(true)->save($this->post)){
            $this->apiReturn(0,'发布失败，请稍后再试');
        }

        $this->apiReturn(1,'发布成功');
    }

    /**
     * [getCoupon 领取优惠券]
     * @return [type] [description]
     */
    public function getCoupon(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $model = model($this->tn)->get(intval($this->post['id']));
        if(is_null($model)){
            $this->apiReturn(0,'该优惠券不存在或已被删除');
        }
        if($model['get_num'] <= 0){
            $this->apiReturn(0,'优惠券已经领完');
        }
        if($model['end_use'] < strtotime(date('Y-m-d'))){
            $this->apiReturn(0,'优惠券已经过期');
        }
        if(db('coupon_get')->where('foreign_key',$model['id'])->where('get_user_id',UID)->find()){
            $this->apiReturn(0,'只能领取一次');
        }
        db()->startTrans();
        if(!$model->setDec('get_num',1)){
            db()->startTrans();
            $this->apiReturn(0,'优惠券扣除失败');
        }
        if(!db('coupon_get')->insert([
            'foreign_key' => $model['id'],
            'issue_user' => $model['user_id'],
            'get_user_id' => UID,
            'coupon_code' => intval(10000+$model['id']+UID),
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'领取失败，请稍后再试');
        }
        db()->commit();
        $jump = $model['jump'] == 3 ? $model['foreign_key'] : $model['user_id'];
        $this->apiReturn(1,'领取成功',[
            'jump_type' => $model['jump'],
            'jump' => $jump
        ]);
    } 

    //核销折扣券
    public function hexiao(){
        if(!isset($this->post['code']) || trim($this->post['code']) === ''){
            $this->apiReturn(0,'请输入核销码');
        }
        $res = db('coupon_get')->where('coupon_code',trim($this->post['code']))->where('issue_user',UID)->where('status',0)->find();
        if(is_null($res)){
            $this->apiReturn(0,'核销码错误');
        }
        $this->apiReturn(1,'操作成功');
    }  

    //我的优惠券
    public function myCoupon(){
        if(!isset($this->post['type']) || !in_array($this->post['type'],[1,2,3])){
            $this->apiReturn(0,'参数错误');
        }
        $list = db('coupon_get')->alias('g') 
            ->join(['bz_coupon' => 'c'],'c.id = g.foreign_key','left')
            ->join(['bz_user' => 'u'],'u.id = c.user_id','left')
            ->where('g.get_user_id',UID)->where('c.type',intval($this->post['type']))
            ->where('g.status',0)
            ->limit(($this->p-1)*config('page'),config('page_size'))
            ->order('g.add_time desc')
            ->field('use_validate,FROM_UNIXTIME(start_use,"%Y-%m-%d") as format_start,FROM_UNIXTIME(end_use,"%Y-%m-%d") as format_end,end_use,z_num,coupon_code,FROM_UNIXTIME(g.add_time,"%Y-%m-%d") as add_time,u.id as user_id,u.nick_name,u.photo_path')
            ->select();

        foreach($list as $key => $val){
            $list[$key]['status'] = 1;
            if($val['end_use'] < strtotime(date('Y-m-d'))){
                $list[$key]['status'] = 2;
            }
        }
        $this->apiReturn(1,'优惠券列表',$list);

    }

    //我发布的优惠券
    public function myIssue(){
        if(!isset($this->post['type']) || !in_array($this->post['type'],[1,2,3])){
            $this->apiReturn(0,'参数错误');
        }
        $where['type'] = $this->post['type'];
        $list = db('coupon')->where('user_id',UID)->where($where)
            ->order('add_time desc')
            ->limit(($this->p-1)*config('page_size'),config('page_size'))
            ->order('add_time desc')
            ->field('id,use_validate,FROM_UNIXTIME(start_use,"%Y-%m-%d") as format_start,end_use,FROM_UNIXTIME(end_use,"%Y-%m-%d") as format_end,z_num')
            ->select();

        foreach($list as $key => $val){
            $list[$key]['status'] = 1;
            if($val['end_use'] < strtotime(date('Y-m-d'))){
                $list[$key]['status'] = 2;
            }
        }
        $this->apiReturn(1,'优惠券',$list);
    }
}
